﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RacePlatformer;
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using RacePlatformer.Object;
using Dwarfs.Manager;
using RacePlatformer.Manager;
using FarseerPhysics.Dynamics.Contacts;
using Microsoft.Xna.Framework.Graphics;

namespace Dwarfs.Object
{
    class SaveState : GameObject
    {
        public Dictionary<int,Vector2> playerPositions;
        Dictionary<GameObject, Vector2> gameObjectPositions;
        public int levelNr;

        public SaveState(MainGame maingame, World world, Vector2 size, Vector2 position, BodyType bodytype, float mass, int levelID)
            : base(maingame, world, size, position, bodytype, mass, levelID)
        {
            this.levelID = levelNr;
            gameObjectPositions = new Dictionary<GameObject, Vector2>();
            playerPositions = new Dictionary<int, Vector2>();
            this.body.OnCollision += OnColl;
        }
        private bool OnColl(Fixture fixtureA, Fixture fixtureB, Contact contact)
        {
            save();
            return true;
        }
        public void save()
        {
            levelNr = levelID;
            playerPositions = new Dictionary<int, Vector2>();
            gameObjectPositions = new Dictionary<GameObject, Vector2>();
            foreach(BasePlayer player in PlayerManager.players){
                playerPositions.Add(player.ID,player.body.Position);
            }
            for (int i = 0; i < maingame.goManager.gameObjects.Count; i++)
            {
                if (maingame.goManager.gameObjects[i].body.BodyType == BodyType.Dynamic)
                {
                    gameObjectPositions.Add(maingame.goManager.gameObjects[i], maingame.goManager.gameObjects[i].body.Position);
                }
            }
            SaveStateManager.pushSaveState(this);
            this.body.Dispose();
        }
        public void load()
        {
            for (int playerCount = 0; playerCount < PlayerManager.players.Count; playerCount++)
            {
               PlayerManager.players[playerCount].body.Position = playerPositions[playerCount];
            }
            for (int i = 0; i < maingame.goManager.gameObjects.Count; i++)
            {
                for (int x = 0; x < gameObjectPositions.Count; x++)
                {
                    if (maingame.goManager.gameObjects[i] == gameObjectPositions.Keys.ElementAt(x))
                    {
                        maingame.goManager.gameObjects[i].body.Position = gameObjectPositions[gameObjectPositions.Keys.ElementAt(x)];
                    }
                }
            }
        }

        public override void LoadContent()
        {
            texture = maingame.Content.Load<Texture2D>("Objects/checkPoint");
        }
    }
}
